<?php

class GalactusModelAccount extends GalactusModelUser {

	function __construct($control) {
		parent::__construct($control);
	}

	public function add($name, $profile_id, $email, $password, $password_confirm, $active) {
		if(filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($password)  && $password == $password_confirm) {
			$email = strtolower($email);
			$name = empty($name)? reset(explode('@', $email)) : $name;
			$active = empty($active)? "" : $active;
			$query = $this->query(
				"INSERT INTO User (name, email, password, profile_id, active, created_on) VALUES (:name, :email, SHA2(SHA2(:password, 512), 512), :profile_id, :active, NOW( ))",
				array(":name" => $name, ":email" => $email, ":password" => $password, ":profile_id" => $profile_id, ":active" => $active)
			);
			if(!$query["fail"])
				echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL."REDIRECT/ACCOUNT/SHOW");
			else throw new Exception("Falha na realização da operação!");
		}
		else throw new Exception("Falha na realização da operação!");

	}

	public function changePassword($user_ids) {
		for($i = 0; $i < count($user_ids); ++$i) {
			$user = end($this->retrieveUser($user_ids[$i]));
			echo $password;
			$query = $this->query("UPDATE User SET password = SHA2(SHA2('".$password."', 512), 512) WHERE id = ".$user_ids[$i]);
			if($query["fail"])
				throw new Exception("Falha na realização da operação!");
			mail($user["email"], "GALACTUS: Nova Senha", "Senha atual: ".$password);
		}
		echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL."REDIRECT/ACCOUNT/SHOW");
	}

	public function changeProfile($params) {
		$profile_id = reset($params);
		array_splice($params, 0, 1);
		$query = $this->query("UPDATE User SET profile_id = ".$profile_id." WHERE id IN (".implode(",", $params).")");
		if(!$query["fail"])
			echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL."REDIRECT/ACCOUNT/SHOW");
		else throw new Exception("Falha na realização da operação!");
	}

	public function remove($user_ids) {
		$query = $this->query("DELETE FROM User WHERE id IN (".implode(",", $user_ids).")");
		if(!$query["fail"])
			echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL.'REDIRECT/ACCOUNT/SHOW');
		else throw new Exception("Falha na realização da operação!");
	}

	public function retrieveProfiles( ) {
		$query = $this->query("SELECT * FROM Profile WHERE id != 1 ORDER BY label");
		if(!$query["fail"] && !empty($query["result"]))
			return $query["result"];
		else throw new Exception("Falha ao recuperar informações dos perfis de usuário!");
	}

}

?>
